package com.ac.util;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

	/**
	 * 通用加密key
	 */
	public static String secret = "ssly123456789api";

	/**
	 * 加密-使用默认key
	 * 
	 * @param plainText
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String plainText) {
		return encrypt(plainText, secret);
	}

	/**
	 * 加密
	 * 
	 * @param plainText
	 * @param secret
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String plainText, String secret) {
		try {
			secret = getSecret(secret);
			SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
			return Base64.getEncoder().encodeToString(encryptedBytes);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 解密-使用默认key
	 * 
	 * @param encryptedText
	 * @param secret
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encryptedText) {
		return decrypt(encryptedText, secret);
	}

	/**
	 * 解密
	 * 
	 * @param encryptedText
	 * @param secret
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encryptedText, String secret) {
		try {
			secret = getSecret(secret);
			SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
			return new String(decryptedBytes, StandardCharsets.UTF_8);
		} catch (Exception e) {
			return null;
		}
	}

	private static String getSecret(String _secret) {
		if (_secret.length() > 16)
			_secret = _secret.substring(0, 16);
		else if (_secret.length() < 16)
			_secret = secret;
		return _secret;
	}
	
}
